﻿using System;
using EchoFramework;
using DG.Tweening;
using UnityEngine;

/// <summary>
/// EchoText组件命令
/// </summary>
public class TextCommand : CommandBase
{
    private EchoText echoTxt;
    private int oldNum;
    private int newNum;
    private float duringTime;
    private float unitTime;
    private float nextRefreshAnimTime;
    private CommandEmptyEnum emptyEnum;
    private CampEnum camp;
    private DiskEnum diskEnum;

    public TextCommand(EchoText commandTxt, int oldNum, int newNum, CampEnum camp, DiskEnum diskEnum,
        CommandEmptyEnum emptyEnum = CommandEmptyEnum.None)
    {
        duringTime = 0.5f;
        unitTime = 0.1f;
        this.echoTxt = commandTxt;
        this.oldNum = oldNum;
        this.newNum = newNum;
        this.camp = camp;
        this.diskEnum = diskEnum;
        this.emptyEnum = emptyEnum;
    }

    public override void ExcuteCommand()
    {
        base.ExcuteCommand();
        DOTween.KillAll();
        switch (emptyEnum)
        {
            case CommandEmptyEnum.None:
                AnimText(true);
                break;
            case CommandEmptyEnum.OldNumIsEmpty:
                echoTxt.text = newNum.ToString();
                break;
            case CommandEmptyEnum.NewNumIsEmpty:
                echoTxt.text = string.Empty;
                break;
        }
    }

    public override void RevocationCommand()
    {
        base.RevocationCommand();
        DOTween.KillAll();
        switch (emptyEnum)
        {
            case CommandEmptyEnum.None:
                AnimText(false);
                break;
            case CommandEmptyEnum.OldNumIsEmpty:
                echoTxt.text = string.Empty;
                break;
            case CommandEmptyEnum.NewNumIsEmpty:
                echoTxt.text = oldNum.ToString();
                break;
        }

        EventManager.Instance.Execute(EventTypeEnum.RevocationCommandNum, camp, diskEnum, oldNum, emptyEnum);
    }

    /// <summary>
    /// 动画改变数字
    /// </summary>
    /// <param name="isExecute">是否是向前执行操作</param>
    private void AnimText(bool isExecute)
    {
        Sequence txtSequece = DOTween.Sequence();
        float oldAnimNum = isExecute ? oldNum : newNum;
        float newAnimNum = isExecute ? newNum : oldNum;
        int retNum = isExecute ? newNum : oldNum;
        txtSequece.Append(DOTween.To((value) =>
            {
                if (TimeManager.TimeSeconedFloat >= nextRefreshAnimTime)
                {
                    nextRefreshAnimTime = TimeManager.TimeSeconedFloat + unitTime;
                    echoTxt.text = value.ToString("0");
                }
            }, oldAnimNum, newAnimNum, duringTime))
            .OnComplete(() => { echoTxt.text = retNum.ToString(); })
            .OnKill(() =>
            {
                echoTxt.text = retNum.ToString();
            });
    }
}